package com.atguigu.interview.algo;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author : Jungle
 * @Description :
 */
public class LruCacheDemo1<K, V> extends LinkedHashMap<K, V> {
    private int capacity;

    //缓存坑位置

    public LruCacheDemo1(int capacity) {
        /**
         * 这里演示用参数最多的
         * 1、LinkedHashMap(int initialCapacity,
         *                          float loadFactor,
         *                          boolean accessOrder)
         *
         *   accessOrder     the ordering mode - <tt>true</tt> for access-order, <tt>false</tt> for insertion-order
         *
         *   true
         *
         *   [1, 2, 3]
         * [2, 3, 4]
         *
         *
         * [2, 4, 3]
         * [2, 4, 3]
         * [2, 4, 3]
         *
         * [4, 3, 5]
         *
         * ======================
         *false
         * [1, 2, 3]
         * [2, 3, 4]
         *
         *
         * [2, 3, 4]
         * [2, 3, 4]
         * [2, 3, 4]
         *
         *
         * [3, 4, 5]
         */
        super(capacity, 0.75f, true);
        this.capacity = capacity;
    }

    /**
     * 限制页面数量
     * <tt>true</tt> if the eldest entry should be removed
     * from the map; <tt>false</tt> if it should be retained.
     */
    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return super.size() > capacity;
    }

    public static void main(String[] args) {
        LruCacheDemo1<Object, Object> lruCacheDemo = new LruCacheDemo1<>(3);
        lruCacheDemo.put(1, "a");
        lruCacheDemo.put(2, "b");
        lruCacheDemo.put(3, "c");
        System.out.println(lruCacheDemo.keySet());
        lruCacheDemo.put(4, "d");
        System.out.println(lruCacheDemo.keySet());
        lruCacheDemo.put(3, "c");
        System.out.println(lruCacheDemo.keySet());
        lruCacheDemo.put(3, "c");
        System.out.println(lruCacheDemo.keySet());
        lruCacheDemo.put(3, "c");
        System.out.println(lruCacheDemo.keySet());
        lruCacheDemo.put(5, "x");
        System.out.println(lruCacheDemo.keySet());
    }

}
